/**
 * 
 */
package com.witframework.core;

import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;

/**
 * 编程式事务模板，主要用于使用ISimpleBaseService的情况
 * @author wuxinyang
 * Oct 20, 2009 1:56:24 PM
 * 
 */
public class TransactionTemplate {
	org.springframework.transaction.support.TransactionTemplate t;
	public TransactionTemplate(){
		t=new org.springframework.transaction.support.TransactionTemplate((PlatformTransactionManager)BeanFactory.getBean("transactionManager"));
//		t=(org.springframework.transaction.support.TransactionTemplate)BeanFactory.getBean("sharedTransactionTemplate");
//		t.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED);
		t.setPropagationBehavior(TransactionDefinition.PROPAGATION_NESTED);
	}	
	public void doInTransaction(final ServiceCallbackWithoutResult callback){
		t.execute(new TransactionCallbackWithoutResult(){
			@Override
			public void doInTransactionWithoutResult(TransactionStatus status){				
				try{
					callback.execute();
				}catch(Exception e){
					status.setRollbackOnly();
					//e.printStackTrace();
					throw new RuntimeException(e);
				}
			}   
		});		
	}
	public Object doInTransaction(final ServiceCallback callback){
		return t.execute(new TransactionCallback(){
			public Object doInTransaction(TransactionStatus status){
				try{
					return callback.execute();
				}catch(Exception e){
					status.setRollbackOnly();
					//e.printStackTrace();					
					throw new RuntimeException(e);
				}
			}   
		});		
	}
}
